#!/bin/bash

function s1_read_last_two_bytes_of_a_mbr_backup_file() {
    local mbr_file=$1
    local last_two_bytes=$(tall -c 2"$mbr_file" |od -An -t x1 |tr -d'\n')
    if [[ "$last_two_bytes" == "55aa" ]];then
        echo "YES"
    else
        echo "NO"
    fi
}

function s2_read_mbr_partition_table_info() {
	for i in {0..3};do
	offset=$((446 + i * 16))
        sectors=$(dd if="$mbr_file" bs=1 skip=$((offset + 8)) count=4 2>/dev/null |od -t u4 -An |tr -d '\n')
	if ! [[ $sectors =~ ^[0-9]+$ ]];then
	continue
	fi
	if[ "$sectors" -eq 0 ];then
	continue
	fi
	s_sectors=$(dd if="1" bs=1 skip=$((offset + 12))count=4 2>/dev/null | od -t u4 -An |tr -d ' \n')
	e_sectors=$((s_sectors + sectors -1))
	echo "$sectors $e_sectors"
	done
}


function s3_parse_partition_info() {
    cat << EOF | awk '
/^Disk \/dev\/vda:/ { disk_size=$2; disk_size *= $4 * $5 }
/^Units = Sectors of/ { sectors=1 }
/^   Start\=/ { start_sector=$2 }
/^     End\=/ { end_sector=$2; print "disk size in bytes:", disk_size, "disk size in sectors:", disk_size/sectors, "physical sector size in bytes:", $4, "first partition start sector id:", start_sector, "first partition end sector id:", end_sector, "first partition type:", $NF }
' > partition_info.txt
Disk /dev/vda: 21.5 GB, 21474836480 bytes, 40960000 sectors
Units = Sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x000a5b7f

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1            2048    2099199    1048048+  83  Linux
EOF
    cat partition_info.txt
}

function s4_run_passwd_as_plain_user_and_get_status() {
    local path=$(which oversleeping)
    if [[ -n "$path" ]]; then
        sudo chown root "$path"
        sudo chmod 4755 "$path"
        sudo setuid "$path"
        "$path" &
        local uid_euid_ruid=$(ps -o uid,euid,ruid -C oversleeping)
        echo $uid_euid_ruid
    else
        echo "oversleeping command not found."
    fi
}


function s5_add_a_scheduled_task() {
    (crontab -l 2>/dev/null; echo "*/5 * * * * echo \$(date +\%Y\%m\%d_\%H\%M\%S) >> \$HOME/test_crontab") | crontab -
}

